package com.company.gobang.module.room.domain;

import com.alibaba.fastjson.JSON;
import com.company.gobang.module.room.RoomConstant;
import com.company.gobang.module.room.event.RoomStartEvent;
import com.company.gobang.proto.EnterRoomPush;
import com.company.gobang.proto.PlayChessPush;
import com.company.gobang.proto.PlayChessReq;
import xyz.noark.core.event.EventHelper;
import xyz.noark.core.network.Sender;
import xyz.noark.core.network.SessionAttrKey;
import xyz.noark.core.network.SessionManager;
import xyz.noark.core.util.MapUtils;
import xyz.noark.core.util.RandomUtils;

import java.util.*;

/**
 * 房间
 *
 * @author 小流氓[176543888@qq.com]
 */
public class Room {
    public static final SessionAttrKey<Integer> attrKey = SessionAttrKey.valueOf(RoomConstant.SESSION_KEY_ROOM_QUEUE_ID);
    private final int id;
    private final Set<String> playerIdSet = new HashSet<>();

    public Room(int id) {
        this.id = id;
    }

    /**
     * 进入房间
     */
    public void enter(String playerId) {
        playerIdSet.add(playerId);

        // 给玩有的Session上绑定这个房间的ID，这样下棋逻辑就可以放另一个队列里执行了
        SessionManager.getSessionByPlayerId(playerId).attr(attrKey).set(id);
    }

    public int getId() {
        return id;
    }

    public void startWork() {
        EventHelper.publish(new RoomStartEvent(id));
        // 摇出一个先手

    }

    public void noticePlayerEnterRoom() {
        EnterRoomPush push = new EnterRoomPush(id);
        Sender.relayPacket(playerIdSet.toArray(new String[0]), "", push);
    }

    public void randomFirstPlayer() {
        List<String> playerIdList = new ArrayList<>(playerIdSet);
        String firstPlayerId = RandomUtils.randomList(playerIdList);

        // 先手
        Sender.relayPacket(firstPlayerId, "", new PlayChessPush("1"));
        boolean remove = playerIdList.remove(firstPlayerId);
        if (remove) {
            Sender.relayPacket(playerIdList.toArray(new String[]{}), "", new PlayChessPush("2"));
        }
    }

    public void syncPlayChessReq(String playerId, PlayChessReq req) {
        // 同步给自己外的其他人
        List<String> playerIdList = new ArrayList<>(playerIdSet);
        playerIdList.remove(playerId);
        if (!playerIdList.isEmpty()) {
            Map<String, Integer> json = MapUtils.newHashMap(3);
            json.put("x", req.getX());
            json.put("y", req.getX());
            json.put("color", req.getColor());
            Sender.relayPacket(playerIdList.toArray(new String[]{}), "", new PlayChessPush(JSON.toJSONString(json)));
        }
    }
}
